package com.juqent.kanban;

import android.app.AlertDialog;
import android.app.Dialog;
import android.content.Context;
import android.content.pm.PackageManager;
import android.content.pm.PermissionInfo;
import android.graphics.Bitmap;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.util.Log;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.Window;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import com.juqent.kanban.databinding.ActivityShowwebBinding;
import java.lang.reflect.Method;


/**
 * @Author Wang
 * @Date 2023/8/14
 */
public class ShowWebActivity extends AppCompatActivity {

    private RelativeLayout text;
    private WebView web;
    private boolean show = false;
    private ActivityShowwebBinding binding;
    private String TAG = "ShowWebActivity";
    private LinearLayout mll;
    private Handler handlerRefresh;
    private Runnable runnableRefresh;
    private String baseurl="";
    private  AlertDialog dialog;
    private SpUtils spUtils;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        spUtils=new SpUtils(this);
        baseurl=spUtils.getBaseUrl();
        binding = ActivityShowwebBinding.inflate(getLayoutInflater());
        setContentView(binding.getRoot());
        initDialog();
    }

   public void initDialog(){
       dialog = new AlertDialog.Builder(this).create();
       //设置点击对话框之外的区域弹窗不消失
       dialog.setCancelable(false);
       dialog.show();
       Window window = dialog.getWindow();
       window.setContentView(R.layout.dialog_urlinsert);
       EditText url=dialog.findViewById(R.id.url);
       url.setText(baseurl);
       dialog.findViewById(R.id.confirm).setOnClickListener(new View.OnClickListener() {
           @Override
           public void onClick(View view) {
               if(url.getText().toString().equals("")){
                   Toast.makeText(ShowWebActivity.this,R.string.input_url,Toast.LENGTH_LONG).show();
               }else {
                   baseurl = url.getText().toString();
                   spUtils.setBaseUrl(baseurl);
                   initWeb();
                   dialog.dismiss();
                   //  设置定时刷新
                     setRefresh();
               }
           }
       });
   }

    public void clearWeb() {
        if(null!=web) {
            web.removeAllViews();
            web.clearHistory();
            web.destroy();
            web.clearCache(true);
        }
    }

    public void initWeb() {
        if(null==web){
            web = new WebView(this);
            WebSettings wSet = web.getSettings();
            web.setWebViewClient(new WebViewClient() {
                @Override
                public void onPageStarted(WebView view, String url, Bitmap favicon) {
                    view.setInitialScale(100);
                    super.onPageStarted(view, url, favicon);
                }
            });
            wSet.setJavaScriptEnabled(true);
            wSet.setDomStorageEnabled(true);
            wSet.setCacheMode(WebSettings.LOAD_NO_CACHE);
            wSet.setAllowFileAccess(true); //设置可以访问文件
            wSet.setJavaScriptCanOpenWindowsAutomatically(true); //支持通过JS打开新窗口
            wSet.setLoadsImagesAutomatically(true); //支持自动加载图片
            wSet.setDefaultTextEncodingName("utf-8");//设置编码格式
            wSet.setAllowUniversalAccessFromFileURLs(true);
            wSet.setAllowFileAccessFromFileURLs(true);
            wSet.setUserAgentString("Mozilla/5.0 (Linux; Android 4.1.2; C1905 Build/15.1.C.2.8) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/34.0.1847.114 Mobile Safari/537.36");
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
                // 允许javascript出错
                try {
                    Method method = Class.forName("android.webkit.WebView").
                            getMethod("setWebContentsDebuggingEnabled", Boolean.TYPE);
                    if (method != null) {
                        method.setAccessible(true);
                        method.invoke(null, true);
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
            web.setLayerType(View.LAYER_TYPE_HARDWARE, null);
            web.loadDataWithBaseURL(null, "", "text/html", "utf-8", null);
            web.clearCache(true);
            mll = findViewById(R.id.webviewLayout);
            LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(
                    LinearLayout.LayoutParams.MATCH_PARENT,
                    LinearLayout.LayoutParams.MATCH_PARENT);

            mll.addView(web, params);
        }
        web.loadUrl(baseurl);

    }

    public void refresh() {
        try {
            web.removeAllViews();
            web.clearHistory();
            web.clearCache(true);
            web.loadUrl(baseurl);
        } catch (Exception e) {
            e.printStackTrace();
            Log.d(TAG, "refreshError");
            clearRefresh();
            clearWeb();
            setRefresh();
            initWeb();
        }
    }

    public void setRefresh() {
        handlerRefresh = new Handler();
        runnableRefresh = new Runnable() {
            @Override
            public void run() {
                refresh();
                handlerRefresh.postDelayed(runnableRefresh, 1000 * 60 * 10);
            }
        };
        handlerRefresh.postDelayed(runnableRefresh, 1000 * 60  * 10);
    }

    public void clearRefresh() {
        handlerRefresh.removeCallbacks(runnableRefresh);
    }


    @Override
    public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        PackageManager packageManager = this.getPackageManager();
        PermissionInfo permissionInfo = null;
        for (int i = 0; i < permissions.length; i++) {
            try {
                permissionInfo = packageManager.getPermissionInfo(permissions[i], 0);
            } catch (PackageManager.NameNotFoundException e) {
                e.printStackTrace();
            }
            CharSequence permissionName = permissionInfo.loadLabel(packageManager);
            if (grantResults[i] == PackageManager.PERMISSION_GRANTED) {
                Log.i(TAG, "您同意了【" + permissionName + "】权限");
            } else {
                Log.i(TAG, "您拒绝了【" + permissionName + "】权限");
            }
        }
    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {

        switch (keyCode) {
            case KeyEvent.KEYCODE_BACK://返回键
                if (event.getRepeatCount() == 0) {
                    dialog.show();
                }
                break;
            default:
                break;
        }
        return super.onKeyDown(keyCode, event);
    }


    @Override
    protected void onDestroy() {
        super.onDestroy();
        handlerRefresh.removeCallbacks(runnableRefresh);
        web.removeAllViews();
        web.destroy();
        web.clearCache(true);
    }

}